<?php

function get($key, $default = null) {
    if (isset($_GET[$key]) && $_GET[$key]) {
        return trim($_GET[$key]);
    }
    return trim($default);
}

function post($key, $default = null) {
    if (isset($_POST[$key]) && $_POST[$key]) {
        return trim($_POST[$key]);
    }
    return trim($default);
}

function cookie($key, $default = null) {
    if (isset($_COOKIE[$key]) && $_COOKIE[$key]) {
        return trim($_COOKIE[$key]);
    }
    return trim($default);
}

function p($var) {
    print_r("<pre>");
    print_r($var);
    print_r("</pre>");
}

function pd($var) {
    p($var);
    die;
}

function redirect($url) {
    header("HTTP/1.1 302 Moved Temporarily");
    header("location: $url");
    die();
}

function send_order() {
    mysql_update('date', array('disabled' => 1), array('date' => $date));
    sleep(15);
    $date = mysql_value("SELECT `date` FROM `date` WHERE `disabled`=0 ORDER by `date` ASC LIMIT 0,1");
    $q = "SELECT `total` FROM `date` WHERE `date` = '" . $date . "'";
    $order = mysql_value($q);
    $order = unserialize($order);
    $to_mail = "bozheville06@gmail.com";
    $title = "Заказ обедов на " . $date;
    $text = "Первых: " . $order['0.4'] . "\nВторых: " . $order['0.5'];
    mail($to_mail, $title, $text);
}

function set_totals($date = "") {
    $date = $date ? $date : date("Y-m-d");
    $q = "SELECT `order` FROM `food` WHERE `date` = '" . $date . "'";
    $order = array("0.4" => 0, "0.5" => 0);
    $totals = mysql_select_array($q);
    foreach ($totals as $key => $value) {
        if ($value['order'] == 1) {
            $order['0.4']++;
            $order['0.5']++;
        } elseif ($value['order'] == 0.5) {
            $order['0.5']++;
        } elseif ($value['order'] == 0.4) {
            $order['0.4']++;
        }
    }
    $order = serialize($order);
    mysql_update("date", array("total" => $order), array("date" => $date));
}

function get_totals($month = "") {
    $year = date("Y");
    $month = $month ? $month : date("m");
    $month = strlen($month) < 2 ? "0" . $month : $month;
    $dates = array();
    $i = 0;
    $user_info = auth();
    while ($i++ < date("t")) {
        $i = $i < 10 ? "0" . $i : $i;
        $dates[$i]['date'] = $year . "-" . $month . "-" . $i;
        $dates[$i]['day'] = date('w', strtotime($dates[$i]['date']));
    }
    foreach ($dates as $k => $date) {
        $total[$date['date']] = array('0.4' => 0, '0.5' => 0);
    }
    $month = $year . $month;
    $q = "SELECT `date`, `total` FROM `date` WHERE `month` = '" . $month . "'";
    $totals = mysql_select_array($q);
    if ($totals) {
        foreach ($totals as $key => $value) {
            $val = unserialize($value['total']);
            $total[$value['date']] = $val ? $val : $total[$value['date']];
        }
    }
    return $total;
}